package com.zsc.wxm.ysh.anjo.house.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.wxm.ysh.anjo.house.cache.ImagesCacheService;
import com.zsc.wxm.ysh.anjo.house.cache.ResourcesCacheService;
import com.zsc.wxm.ysh.anjo.house.feign.MemberService;
import com.zsc.wxm.ysh.anjo.house.mapper.RentHouseMapper;
import com.zsc.wxm.ysh.anjo.house.model.Estate;
import com.zsc.wxm.ysh.anjo.house.model.Promise;
import com.zsc.wxm.ysh.anjo.house.model.RentHouse;
import com.zsc.wxm.ysh.anjo.house.model.Resources;
import com.zsc.wxm.ysh.anjo.house.service.EstateService;
import com.zsc.wxm.ysh.anjo.house.service.PromiseService;
import com.zsc.wxm.ysh.anjo.house.service.RentHouseService;
import com.zsc.wxm.ysh.anjo.house.service.ResourcesService;
import com.zsc.wxm.ysh.anjo.house.utils.CodeUtil;
import com.zsc.wxm.ysh.anjo.result.PageResult;
import com.zsc.wxm.ysh.anjo.result.Result;
import com.zsc.wxm.ysh.anjo.service.base.enums.resources.RentHouseStatus;
import com.zsc.wxm.ysh.anjo.service.base.model.member.bo.MemberBO;
import com.zsc.wxm.ysh.anjo.service.base.model.resources.dto.RentHouseDTO;
import com.zsc.wxm.ysh.anjo.service.base.model.resources.qo.RentHouseQuery;
import com.zsc.wxm.ysh.anjo.service.base.model.resources.vo.RentHouseVO;
import com.zsc.wxm.ysh.anjo.utils.MyDateUtil;
import com.zsc.wxm.ysh.anjo.utils.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述：
 *
 * @author playmaker
 * @since 2021/2/24 23:08
 */
@Service
@Slf4j
public class RentHouseServiceImpl extends ServiceImpl<RentHouseMapper, RentHouse> implements RentHouseService {

    @Resource
    private ResourcesService resourcesService;

    @Resource
    private ResourcesCacheService resourcesCacheService;

    @Resource
    private MemberService memberService;

    @Resource
    private PromiseService promiseService;

    @Resource
    private EstateService estateService;

    @Resource
    private CodeUtil codeUtil;

    @Resource
    private ImagesCacheService imagesCacheService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(RentHouseDTO params) {
        RentHouse rentHouse = new RentHouse();
        BeanUtils.copyProperties(params, rentHouse);
        rentHouse.setStatus(RentHouseStatus.OVERDUE.getValue());
        //编码自动生成
        rentHouse.setCode(codeUtil.getSquenceCode().replace("ANJO", ""));
        baseMapper.insert(rentHouse);
    }

    @Override
    public PageResult listByPage(RentHouseQuery query) {
        Page<RentHouse> page = new Page<>(query.getCurrPage(), query.getPageSize());
        LambdaQueryWrapper<RentHouse> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if (query.getStatus() != null) {
            lambdaQueryWrapper.eq(RentHouse::getStatus, query.getStatus());
        }
        if (query.getRentUserId() != null) {
            lambdaQueryWrapper.eq(RentHouse::getRentUserId, query.getRentUserId());
        }
        if (query.getCreateTimeStart() != null) {
            lambdaQueryWrapper.ge(RentHouse::getCreateTime, query.getCreateTimeStart());
        }
        if (query.getCreateTimeEnd() != null) {
            lambdaQueryWrapper.le(RentHouse::getCreateTime, query.getCreateTimeEnd());
        }
        if (StringUtils.isNotBlank(query.getCode())) {
            lambdaQueryWrapper.like(RentHouse::getCode, query.getCode());
        }
        page = this.baseMapper.selectPage(page, lambdaQueryWrapper);
        List<RentHouse> rentHouses = page.getRecords();
        if (CollUtil.isEmpty(rentHouses)) {
            return PageResult.ok(Collections.emptyList(), 0);
        }
        log.info("rentHouses长度=>{}", rentHouses.size());
        //搜集房源ids
        List<Long> houseIds = rentHouses.stream().map(RentHouse::getResourcesId).collect(Collectors.toList());
        //搜集租客ids
        List<Long> rentUserIds = rentHouses.stream().map(RentHouse::getRentUserId).collect(Collectors.toList());

        //批量获取房源
        List<Resources> resources = new ArrayList<>();
        houseIds.forEach(x -> resources.add(resourcesCacheService.getByIdCache(x)));
        //批量获取租客信息
        Result result = memberService.getListByIds(rentUserIds);
        String jsonData = JSON.toJSONString(result.getData().get("list"));
        List<MemberBO> memberBos = JSON.parseArray(jsonData, MemberBO.class);
        //批量获取合约信息
        List<Promise> promises = promiseService.getListByHouseIds(houseIds);
        log.info("合约数据长度=>{}", promises.size());
        //批量获取楼盘信息
        List<Long> estateIds = resources.stream().map(Resources::getEstateId).collect(Collectors.toList());
        List<Estate> estates = new ArrayList<>();
        estateIds.forEach(x -> estates.add(estateService.getOneById(x)));

        List<RentHouseVO> list = new ArrayList<>();
        for (int i = 0;i < rentHouses.size();i++) {
            RentHouseVO rentHouseVo = new RentHouseVO();
            rentHouseVo.setId(rentHouses.get(i).getId());
            rentHouseVo.setHouseId(resources.get(i).getId());
            rentHouseVo.setAddress(estates.get(i).getCity() + estates.get(i).getCity() + estates.get(i).getAddress());
            rentHouseVo.setCode(rentHouses.get(i).getCode());
            rentHouseVo.setFacilities(resources.get(i).getFacilities());
            rentHouseVo.setHostName(resources.get(i).getConstact());
            rentHouseVo.setHostPhone(resources.get(i).getPhone());
            rentHouseVo.setRentUsername(memberBos.get(i).getUsername());
            rentHouseVo.setRentUserPhone(memberBos.get(i).getPhone());
            rentHouseVo.setPromiseTime(MyDateUtil.getLocalDateTimeYYMMDDStr(promises.get(i).getCreateTime()) + "-" +
                    MyDateUtil.getLocalDateTimeYYMMDDStr(promises.get(i).getEndTime()));
            rentHouseVo.setRent(resources.get(i).getRent() + "元/月");
            rentHouseVo.setStatus(RentHouseStatus.getEnumDesc(rentHouses.get(i).getStatus()));
            rentHouseVo.setHouseTitle(resources.get(i).getTitle());
            rentHouseVo.setImage(imagesCacheService.listByResourcesIdCache(resources.get(i).getId()).get(0).getImageUrl());
            list.add(rentHouseVo);
        }
        PageUtil pageUtil = new PageUtil(page);
        return PageResult.ok(list, pageUtil.getTotal());
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        LambdaUpdateWrapper<RentHouse> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(RentHouse::getId, id).set(RentHouse::getStatus, status);
        this.update(updateWrapper);
    }


}
